// -*-mode:c++; coding:utf-8-*-

#ifndef _XBASE_TABLET_NAME_PARSER_HPP_
#define _XBASE_TABLET_NAME_PARSER_HPP_

#include <string>

#include "constants.hpp"
#include "xbase_utility.hpp"

namespace xbase
{
	// 实现方式改为不保存字符串，只解析给定字符串内容！
	class tablet_name_parser
	{
	public:
		static const uint64_t bad_tablet_id;
		static const uint64_t root_meta_tablet_id = 0;

		static const char s_comma_char;
		static const std::string s_root_meta_tablet_name;

	public:
		tablet_name_parser()
			: m_string_begin(NULL)
			, m_string_end(NULL)
			, m_size(0)
			, m_first_comma(NULL)
			, m_last_comma(NULL)
			, m_tablet_id(bad_tablet_id) {}

		template<typename string_type> // string_type::data(), string_type::size()
		explicit
		tablet_name_parser(const string_type &tablet_name)
			: m_string_begin(tablet_name.data())
			, m_string_end(tablet_name.data() + tablet_name.size())
			, m_size(tablet_name.size())
			, m_first_comma(tablet_name.data()) // set to be m_string_begin
			, m_last_comma(tablet_name.data() + tablet_name.size())
			, m_tablet_id(bad_tablet_id) { // set to be m_string_end
			parse();
		}

		tablet_name_parser(const tablet_name_parser &other)
			: m_string_begin(other.m_string_begin)
			, m_string_end(other.m_string_end)
			, m_size(other.m_size)
			, m_first_comma(other.m_first_comma)
			, m_last_comma(other.m_last_comma)
			, m_tablet_id(other.m_tablet_id) {}

		inline
		tablet_name_parser &operator=(const tablet_name_parser &other) {
			if(&other != this)
			{
				m_string_begin = other.m_string_begin;
				m_string_end = other.m_string_end;
				m_size = other.m_size;
				m_first_comma = other.m_first_comma;
				m_last_comma = other.m_last_comma;
				m_tablet_id = other.m_tablet_id;
			}
			return *this;
		}

		std::string table_name() const {
			return ((m_tablet_id == root_meta_tablet_id)
				? s_root_meta_tablet_name
				: std::string(m_string_begin, m_first_comma));
		}
		
		std::string start_row() const {
			return ((m_tablet_id == root_meta_tablet_id)
				? std::string()
				: dump_string_unhex(m_first_comma + 1,
						    (m_last_comma - (m_first_comma + 1))));
			// return std::string(m_first_comma + 1,
			// 		   m_last_comma);
		}

		uint64_t tablet_id() const {
			return m_tablet_id;
		}

	protected:
		void parse();

	private:
		const char * m_string_begin;
		const char * m_string_end;
		std::size_t m_size;
		const char * m_first_comma; // == m_string_begin, or point to first ','
		const char * m_last_comma;  // == m_string_end, or point to last ','
		uint64_t m_tablet_id;
	};

} // namespace xbase

#endif	// _XBASE_TABLET_NAME_PARSER_HPP_
